/*
 Copyright 2007 Razvan Taranu

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
package generators;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.thoughtworks.qdox.model.JavaClass;
import com.thoughtworks.qdox.model.JavaMethod;
import com.thoughtworks.qdox.model.JavaParameter;
import com.thoughtworks.qdox.model.JavaSource;
import com.thoughtworks.qdox.model.Type;

public class PhpServices {
    private final Log log = LogFactory.getLog(PhpServices.class);

    private static final String serviceTemplate;
    static {
        serviceTemplate = Utils.readRessource("templates/php/services/ServiceTemplate.tpl");
    }

    private static final String methodTemplate;
    static {
        methodTemplate = Utils.readRessource("templates/php/services/MethodTemplate.tpl");
    }

    public void run() {
        log.info("generating PHP services");

        List<String> services = new ArrayList<String>();

        for (JavaSource source : JavaHelper.getRemoteServiceSources()) {
            log.info("processing " + source.getURL());

            JavaClass javaClass = source.getClasses()[0];

            String content = generate(javaClass);

            String serviceName = javaClass.getName();
            services.add(serviceName);

            PhpHelper.writeService(serviceName, content);
        }
    }

    private String generate(JavaClass javaClass) {
        List<String> methodDeclarations = new ArrayList<String>();
        List<String> methodCalls = new ArrayList<String>();

        for (JavaMethod method : javaClass.getMethods()) {
            String prettyPrint = prettyPrint(method);
            String methodDeclaration = methodDeclaration(method);

            String string = "    # " + prettyPrint;
            string += "\n    " + methodDeclaration;
            methodDeclarations.add(string);

            methodCalls.add(methodCall(method));
        }

        String output = serviceTemplate;

        output = output.replace("@@serviceName@@", javaClass.getName());
        output = output.replace("@@methodDeclarations@@", StringUtils.join(methodDeclarations, "\n\n"));
        output = output.replace("@@methodCalls@@", StringUtils.join(methodCalls, "            } else"));

        return output;
    }

    private String methodCall(JavaMethod method) {
        List<String> argv = new ArrayList<String>();
        for (JavaParameter param : method.getParameters()) {
            String value = "array_shift($params)";
            Type type = param.getType();

            String toPhp = PhpHelper.valueToPhp(value, type);

            String string = "$argv[] = " + toPhp + "; # " + param.getName();
            argv.add(string);
        }

        String argvJsonize = StringUtils.join(argv, "\n                ");

        String value = "$result";
        Type type = method.getReturns();

        String resultJsonize = "";
        if ("void".equals(type.getValue())) {
            resultJsonize = "$jsonResult = null;";
        } else {
            String toJson = PhpHelper.valueToJson(value, type);

            resultJsonize = "$jsonResult = " + toJson + ";";
        }

        String output = methodTemplate;

        output = output.replace("@@methodName@@", method.getName());
        output = output.replace("@@argvJsonize@@", argvJsonize);
        output = output.replace("@@resultJsonize@@", resultJsonize);

        return output;
    }

    private String methodDeclaration(JavaMethod method) {
        String declaration = "abstract function " + method.getName() + "(";

        List<String> paramNames = new ArrayList<String>();
        for (JavaParameter param : method.getParameters()) {
            paramNames.add("$" + param.getName());
        }

        declaration += StringUtils.join(paramNames, ", ");
        declaration += ");";

        return declaration;
    }

    private String prettyPrint(JavaMethod method) {

        String prettyPrint = method.getReturns().getGenericValue();
        prettyPrint += (method.getReturns().isArray()) ? "[] " : " ";

        prettyPrint += method.getName() + "(";

        List<String> params = new ArrayList<String>();
        for (JavaParameter param : method.getParameters()) {

            String arg = param.getType().getGenericValue();
            arg += (param.getType().isArray()) ? "[] " : " ";
            arg += param.getName();

            params.add(arg);
        }

        prettyPrint += StringUtils.join(params, ", ");
        prettyPrint += ")";

        return prettyPrint;
    }
}
